package com.pzhu.interceptors;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.pzhu.entity.Online;
import com.pzhu.service.OnlineService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.time.LocalDate;
import java.util.Date;

@Component
@WebListener
public class OnlineListener implements HttpSessionListener {
    @Autowired
    private OnlineService onlineService;

    @Override
    public void sessionCreated(HttpSessionEvent se) {

        UpdateWrapper<Online> onlineUpdateWrapper = new UpdateWrapper<>();
        onlineUpdateWrapper.setSql("onlinecount = onlinecount + 1");
        onlineUpdateWrapper.between("date", LocalDate.now().atStartOfDay(), LocalDate.now().atTime(23, 59, 59));
        boolean update = onlineService.update(onlineUpdateWrapper);
        if (!update) {
            Online online = new Online(new Date(System.currentTimeMillis()), 1, 0);
            onlineService.save(online);
        }
        HttpSessionListener.super.sessionCreated(se);
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        UpdateWrapper<Online> onlineUpdateWrapper = new UpdateWrapper<>();
        onlineUpdateWrapper.setSql("onlinecount = onlinecount - 1");
        onlineUpdateWrapper.between("date", LocalDate.now().atStartOfDay(), LocalDate.now().atTime(23, 59, 59));
        boolean update = onlineService.update(onlineUpdateWrapper);
        if (!update) {
            Online online = new Online(new Date(System.currentTimeMillis()), 0, 0);
            onlineService.save(online);
        }
        HttpSessionListener.super.sessionDestroyed(se);
    }
}
